package com.servlet.control;

import com.bean.Course;
import com.jdbc.util.DButil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet(
        name = "SelectCourseServlet",
        urlPatterns = {"/SelectCourseServlet"})
public class SelectCourseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        DButil db = new DButil();

        List<Course> courses = new ArrayList<>();
        ResultSet rs = db.getResultSet("select * from course");

        try {
            while (rs.next()) {
                String courseId = rs.getString("course_id");
                String courseName = rs.getString("course_name");
                String teacher = rs.getString("teacher");
                int point = Integer.parseInt(rs.getString("point"));
                String time1 = rs.getString("time_1");
                String time2 = rs.getString("time_2");
                String location = rs.getString("location");
                int limited = Integer.parseInt(rs.getString("limited"));
                Course course =
                        new Course(courseId, courseName, teacher, point, time1, time2, location, limited);
                courses.add(course);
            }

            request.setAttribute("courses", courses);
            request.getRequestDispatcher("/jsp/selectCourse.jsp").forward(request, response);

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
